import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:study_flutter/yzhg/project/service/service_method.dart';
import 'package:study_flutter/yzhg/project/shop/pages/home/YFloorContent.dart';
import 'package:study_flutter/yzhg/project/shop/pages/home/YFloorTitle.dart';
import 'package:study_flutter/yzhg/project/shop/pages/home/YRecommend.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'home/AdBanner.dart';
import 'home/LeaderPhone.dart';
import 'home/TopNavigator.dart';
import 'home/swiper_banner.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePage createState() => _HomePage();
}

/*
* AutomaticKeepAliveClientMixin  保持页面效果
* */
class _HomePage extends State<HomePage> with AutomaticKeepAliveClientMixin {
  /* 保持页面效果*/
  @override
  bool get wantKeepAlive => true;

  /*上拉加载page页码*/
  int page = 1;

  /*热销产品数组*/
  List<Map> hotGoodsList = [];

  var _getHomePageFuture;

  @override
  void initState() {
    super.initState();
    _getHomePageFuture = getHomePageContent();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("百姓生活+")),
      //FutureBuilder 异步请求 渲染页面
      body: FutureBuilder<String>(
          key: Key("HomePage"),
          //future接收异步方法
          future: _getHomePageFuture,
          // ignore: missing_return
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            //判断是否有值
            if (snapshot.hasData) {
              var data = json.decode(snapshot.data.toString());
              List<Map> swiper = (data['data']['slides'] as List).cast();
              List<Map> category = (data['data']['category'] as List).cast();
              String adUrlStr =
                  data['data']['advertesPicture']['PICTURE_ADDRESS'];
              String leaderImage = data['data']['shopInfo']['leaderImage'];
              String leaderPhone = data['data']['shopInfo']['leaderPhone'];
              List<Map> recommendListData =
                  (data['data']['recommend'] as List).cast();
              String floorTitle = data['data']['floor1Pic']['PICTURE_ADDRESS'];

              String floor2Title = data['data']['floor2Pic']['PICTURE_ADDRESS'];
              String floor3Title = data['data']['floor3Pic']['PICTURE_ADDRESS'];
              List<Map> floor1 = (data['data']['floor1'] as List).cast();
              List<Map> floor2 = (data['data']['floor2'] as List).cast();
              List<Map> floor3 = (data['data']['floor3'] as List).cast();
              print("获取到广告地址" + adUrlStr);
              return EasyRefresh(
                //自定义footer
                child: ListView(
                  children: <Widget>[
                    SwiperBanner(swiperDataList: swiper),
                    TopNavigator(navigatorList: category),
                    AdBanner(adPicture: adUrlStr),
                    LeaderPhone(
                        leaderImage: leaderImage, leaderPhone: leaderPhone),
                    YRecommend(recommendList: recommendListData),
                    YFloorTitle(pictureAddress: floorTitle),
                    YFloorContent(floorGoodsList: floor1),
                    YFloorTitle(pictureAddress: floor2Title),
                    YFloorContent(floorGoodsList: floor2),
                    YFloorTitle(pictureAddress: floor3Title),
                    YFloorContent(floorGoodsList: floor3),
                    _hotGoods()
                  ],
                ),
                onRefresh: () async {},
                onLoad: () async {
                  print("======================触发了上拉加载======================");
                  getHomePageBelowContent(page.toString()).then((val) {
                    var data = json.decode(val.toString());
                    print(data);
                    List<Map> newGoodsList = (data['data'] as List).cast();
                    setState(() {
                      hotGoodsList.addAll(newGoodsList);
                      page++;
                    });
                  });
                },
              );
            } else {
              return Center(
                child: Text("没有数据"),
              );
            }
          }),
    );
  }

  //获取热销产品
/*  void _getHotGoods() {
    getHomePageBelowContent(page.toString()).then((val) {
      var data = json.decode(val.toString());
      print(data);
      List<Map> newGoodsList = (data['data'] as List).cast();
      setState(() {
        hotGoodsList.addAll(newGoodsList);
        page++;
      });
    });
  }*/

  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
    alignment: Alignment.center,
    color: Colors.transparent,
    child: Text(
      "火爆专区",
      style: TextStyle(fontSize: 16, color: Colors.blue),
    ),
  );

  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
          onTap: () {},
          child: Container(
            width: ScreenUtil().setWidth(370),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(val['image'], width: ScreenUtil().setWidth(368)),
                Text(val['name'],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.pink,
                        fontSize: ScreenUtil().setSp(26.0))),
                Row(
                  children: <Widget>[
                    Text("￥${val['mallPrice']}"),
                    Text(
                      "￥${val['price']}",
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text("没有数据");
    }
  }

  Widget _hotGoods() {
    return Container(
      child: Column(
        children: <Widget>[hotTitle, _wrapList()],
      ),
    );
  }
}
